/*
  每人惠请求的总入口
 */
const tokenExpireFlag = 401;
const duYunTokenExpireFlag = 401;
let innerApp = null;
import {
  MRDCommonConst,
  debounce
} from '../utils/util.js'
const DuYunCommonConst = require('./DuYunCommonConst.js')
// const baseURL = "https://uat.mazn.mingansy.com";// 测试环境
const baseURL = "https://mazn.mingansy.com"; // 正式环境
const BaseRequestModel = {
  url: '',
  param: {},
  method: 'POST',
  hideLoading: false,
  checkUserId: true,
  head: {
    'Content-Type': 'application/json',
  },
  success: () => {},
  failed: () => {}
}

function init(app) {
  innerApp = app
}


/**
 * 
 * @param {请求的参数} reqModel;自带了默认header;特殊需求的额外传
 * @param {如果需要自定义head;多传自定义的header过来} header 
 */
const LMAsyncUploadReq = (reqModel, customerHeader) => {
  return new Promise((resolve, reject) => {
    const start = new Date().getTime();

    if (reqModel.hideLoading === false) {
      wx.showLoading({
        title: '加载中...',
      })
    }
    const header = {
      ...reqModel.head,
      Authorization: wx.getStorageSync(DuYunCommonConst.loginTokenStoreKey),
      ...customerHeader
    }
    console.log('url:', reqModel.url, 'method', reqModel.method, 'param:', reqModel.param, 'header:', header);

    wx.uploadFile({
      url: reqModel.url,
      filePath: reqModel.param.file,
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data'
      },
      formData: {
        ...reqModel.param
      },
      success: res => {
        wx.hideLoading({
          success: (res) => {},
        })
        const end = new Date().getTime();
        console.log('url:' + reqModel.url + "耗时:" + (end - start) + 'ms');
        console.log('请求结果:', res.data);
        if (res.code === duYunTokenExpireFlag) {
          var app = innerApp;
          debounce(() => {
            app && app.loginInSystem && app.loginInSystem();
          }, 1000);
        } else if (res.status === 200) { // 正常返回

        } else { // 其他业务上的错误

        }
        resolve && resolve(res);
      },
      fail: f => {
        wx.hideLoading({
          success: (res) => {},
        })
        reject && reject(f)
      }
    })
  })
}
/**
 * 
 * @param {请求的参数} reqModel;自带了默认header;特殊需求的额外传
 * @param {如果需要自定义head;多传自定义的header过来} header 
 */
const LMAsyncPostReq = (reqModel, customerHeader) => {
  return new Promise((resolve, reject) => {
    const start = new Date().getTime();
    const userId = wx.getStorageSync('userId')
    const header = {
      ...reqModel.head,
      ...customerHeader
    }
    const param = {
      ...reqModel.param,
      userid: userId
    }
    console.log('url:', reqModel.url, 'method', reqModel.method, 'param:', param, 'header:', header);
    if (reqModel.checkUserId) { //是否检查userId为空
      if (userId == null || userId.length == 0) { // 判断userId为空情况未登录;直接返回登录去
        var app = innerApp;
        debounce(() => {
          app && app.loginInSystem && app.loginInSystem();
        }, 1000);
        return
      }
     
    }
    if (reqModel.hideLoading === false) {
      wx.showLoading({
        title: '加载中...',
      })
    }
    wx.request({
      url: reqModel.url,
      method: reqModel.method,
      data: param,
      header: header,
      success: res => {

        wx.hideLoading({
          success: (res) => {},
        })
        const end = new Date().getTime();
        console.log('url:' + reqModel.url + "耗时:" + (end - start) + 'ms');
        console.log('请求结果:', res.data);
        // token 过期
        if (res.data.code === duYunTokenExpireFlag) {
          var app = innerApp;
          debounce(() => {
            app && app.loginInSystem && app.loginInSystem();
          }, 1000);
        } else if (res.data.code === 200) { // 正常返回

        } else { // 其他业务上的错误

        }
        resolve && resolve(res);
      },
      fail: f => {

        wx.hideLoading({
          success: (res) => {},
        })
        reject && reject(f)
      }
    })
  })
}




const asynPostRequest = (url, param = {}, method = 'POST', hideLoading = false) => {
  return new Promise((reslove, reject) => {
    var start = new Date().getTime();
    var head = {
      contentType: 'application/json',
      coreToken: wx.getStorageSync(MRDCommonConst.loginTokenKey)
    }
    console.log('url:' + url + ',param:' + JSON.stringify(param));
    if (hideLoading == false) {
      wx.showToast({
        title: '加载中...',
        icon: 'loading',
        duration: 2500
      })
    }
    wx.request({
      url: url,
      method: method,
      data: param,
      header: head,
      success: res => {
        var end = new Date().getTime();
        console.log('url:' + url + "耗时:" + (end - start) + 'ms');
        console.log(res.data);
        if (res.data.code == 0) {
          reslove && reslove(res.data);
        } else if (res.data.code == tokenExpireFlag) {
          var that = this;
          var app = global.app;
          debounce(() => {
            wx.showLoading({
              title: '登录...',
            })
            app.loginInSystem();
          }, 1000);
        } else {
          debounce(() => {
            wx.showToast({
              icon: 'none',
              title: res.data
            })
          }, 1000);
          reslove && reslove(null)
        }

      },
      fail: res => {
        var end = new Date().getTime();
        console.log('url:' + url + "耗时:" + (end - start) + 'ms');
        console.log(res);
        debounce(() => {
          wx.showToast({
            icon: 'none',
            title: '网络异常'
          })
        }, 1000);
        reslove && reslove(null)
      },
      complete: function () {
        wx.hideToast()
      }
    })
  })
}
const asynWXLogin = (param = {}, method = 'POST') => {
  return new Promise((reslove, reject) => {
    var start = new Date().getTime();
    wx.login({
      success: (res) => {
        var end = new Date().getTime();
        console.log('wx.login()' + "耗时:" + (end - start) + 'ms');
        reslove && reslove(res)
      },
      fail: (err) => {
        var end = new Date().getTime();
        console.log('wx.login()' + "耗时:" + (end - start) + 'ms');
        reject && reject(err);
      }
    })
  })
}



module.exports = {
  init,
  baseURL: baseURL,
  LMAsyncPostReq,
  LMAsyncUploadReq,
  BaseRequestModel,
  MRDCommonConst,
  DuYunCommonConst,
  asynWXLogin: asynWXLogin,
};